package org.ykh.common.utils;



import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.io.entity.EntityUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * HttpClient类 微信：
 *
 */
public class HttpClientUtil {

    public static String doGet(String url)   {

        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建http GET请求
        HttpGet httpGet = new HttpGet(url);
        try {
            // 执行请求
            return httpclient.execute(httpGet, (response -> {
                if (response.getCode() == HttpStatus.SC_OK) {
                    HttpEntity entity = response.getEntity();
                    return EntityUtils.toString(entity, "UTF-8");
                }
                return null;
            }));
        } catch (IOException exception) {
            exception.printStackTrace();
        }
        return null;
    }


    public static void download(String url,String fileName)   {

        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建http GET请求
        HttpGet httpGet = new HttpGet(url);

        try {
            // 执行请求
            httpclient.execute(httpGet,response->{
                // 判断返回状态是否为200
                if (response.getCode() == HttpStatus.SC_OK) {
                    HttpEntity entity = response.getEntity();
                    // String result = EntityUtils.toString(entity, "UTF-8");
                    byte[] bytes = EntityUtils.toByteArray(entity);
                    File file =new File(fileName);
                    //  InputStream in = entity.getContent();
                    try (FileOutputStream fout = new FileOutputStream(file);){
                        fout.write(bytes);
                        fout.flush();
                    }
                }
                return null;
            });
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
